package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.server.mapper.PaperMapper;
import com.tanhua.server.mapper.PaperOptionsMapper;
import com.tanhua.server.mapper.PaperQuestionsMapper;
import com.tanhua.server.mapper.ReportMapper;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TestSoulService {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private PaperQuestionsMapper paperQuestionsMapper;
    @Autowired
    private PaperOptionsMapper paperOptionsMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private UserInfoService userInfoService;

    public ResponseEntity getQuestion() {
        try {
            //查询所有问卷
            List<Paper> papers = paperMapper.selectList(new QueryWrapper<>());
            //遍历问卷
            for (Paper paper : papers) {
                String paperId = paper.getId();

                //根据问卷id获取题目
                QueryWrapper<PaperQuestions> query = new QueryWrapper<>();
                query.eq("pid", paperId);
                List<PaperQuestions> questions = paperQuestionsMapper.selectList(query);

                //将获取的所有题目打乱，随机生成十道题
                Collections.shuffle(questions);
                List<PaperQuestions> newQuestions = new ArrayList<>();
                for (int i = 1; i <= 10; i++) {
                    if (questions.size() > 0) {
                        PaperQuestions questions1 = questions.remove(0);
                        newQuestions.add(questions1);
                    }
                }

                //遍历题目 根据题目id获取对应所有选项
                if (newQuestions.size() > 0) {
                    for (PaperQuestions questions1 : newQuestions) {
                        String qid = questions1.getId();
                        QueryWrapper<PaperOptions> query1 = new QueryWrapper<>();
                        query1.eq("qid", qid);
                        List<PaperOptions> options = paperOptionsMapper.selectList(query1);
                        //给返回前端的option字段赋值
                        for (PaperOptions option : options) {
                            option.setOption(option.getOptions());
                        }
                        //将选项列表赋给对应题目
                        questions1.setOptions(options);
                    }
                }

                //将题目列表赋给对应题目
                paper.setQuestions(newQuestions);
                //假设开始所有问卷都锁柱
                paper.setIsLock(1);
                if("初级".equals(paper.getLevel())){
                    paper.setIsLock(0);
                }else if("中级".equals(paper.getLevel())){
                    //根据用户id和问卷id查询结果表 若结果表存在说明已经做过此问卷，并解锁下一等级的问卷
                    QueryWrapper<Report> query1 = new QueryWrapper<>();
                    query1.eq("user_id", UserThreadLocal.get().getId());
                    query1.eq("paper_id", "1");
                    List<Report> reports = reportMapper.selectList(query1);
                    if(reports.size()>0){
                        paper.setIsLock(0);
                    }
                }else if("高级".equals(paper.getLevel())){
                    QueryWrapper<Report> query2 = new QueryWrapper<>();
                    query2.eq("user_id", UserThreadLocal.get().getId());
                    query2.eq("paper_id", "2");
                    List<Report> reports = reportMapper.selectList(query2);
                    if(reports.size()>0){
                        paper.setIsLock(0);
                    }
                }
            }
            return ResponseEntity.ok(papers);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    public ResponseEntity submitPaper(AnswerList answers) {
        try {
            Report report = new Report();
            User user = UserThreadLocal.get();
            report.setUserId(user.getId().toString());

            //遍历作答列表 根据选项id统计得分
            List<Answers> answersList = answers.getAnswers();
            Integer total = 0;
            for (Answers eachAnswer : answersList) {
                String optionId = eachAnswer.getOptionId();
                PaperOptions options = paperOptionsMapper.selectById(optionId);
                if (options!=null) {
                    total += options.getScore();
                }
            }
            report.setScore(total);

            //根据得分判断所属类型
            Integer reportType = null;
            if (total <= 20) {
                reportType = 1;//猫头鹰
            } else if (total <= 40) {
                reportType = 2;//兔子
            } else if (total <= 55) {
                reportType = 3;//狐狸型
            } else {
                reportType = 4;//狮子型
            }
            report.setReportType(reportType);

            //获取第一道题id查询所属问卷id
            String questionId = answers.getAnswers().get(0).getQuestionId();
            QueryWrapper<PaperQuestions> query = new QueryWrapper<>();
            query.eq("id", questionId);
            PaperQuestions questions = paperQuestionsMapper.selectOne(query);
            String pid = questions.getPid();
            report.setPaperId(pid);

            //删除之前做过的问卷结果 然后保存新结果
            QueryWrapper<Report> queryIsExist = new QueryWrapper<>();
            queryIsExist.eq("user_id", user.getId().toString()).eq("paper_id", pid);
            reportMapper.delete(queryIsExist);
            reportMapper.insert(report);

            return ResponseEntity.ok(report.getId().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    public ResponseEntity getReport(String reportId) {

        try {
            //根据报告id获取报告结果
            Report report = reportMapper.selectById(Integer.parseInt(reportId));
            if (report == null) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
            User user = UserThreadLocal.get();

            //创建一个返给前端的结果对象
            ReportVo reportVo = new ReportVo();

            //根据结果类型获取所有相同类型的用户id
            Integer type = report.getReportType();
            QueryWrapper<Report> query = new QueryWrapper<>();
            query.eq("report_type", type);
            List<Report> reportList = reportMapper.selectList(query);
            List<Long> userIds = new ArrayList<>();
            if (reportList != null && reportList.size() > 0) {
                for (Report report1 : reportList) {
                    Long userId = Long.valueOf(report1.getUserId());
                    //排除重复id和自己的id
                    if ((!userIds.contains(userId)) && !userId.equals(user.getId())) {
                        userIds.add(userId);
                    }
                }
            }

            //根据用户id查询头像
            List<SimilarYou> list = new ArrayList<>();
            for (Long id : userIds) {
                UserInfo userInfo = userInfoService.queryUserinfoById(id);
                SimilarYou similarYou = new SimilarYou(userInfo.getUserId().intValue(), userInfo.getLogo());
                list.add(similarYou);
            }
            reportVo.setSimilarYou(list);

            //评测维度功能未实现，随机生成
            List<Dimensions> dimensionsList = getDimensions();
            reportVo.setDimensions(dimensionsList);

            //根据结果类型填充鉴定结果和鉴定图片
            if (type == 1) {
                reportVo.setConclusion("猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
            } else if (type == 2) {
                reportVo.setConclusion("白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
            } else if (type == 3) {
                reportVo.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            } else if (type == 4) {
                reportVo.setConclusion("狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
                reportVo.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
            }
            return ResponseEntity.ok(reportVo);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    private List<Dimensions> getDimensions() {
        List<Dimensions> dimensionsList = new ArrayList<>();
        List<String> keys = new ArrayList<>();
        keys.add("外向");
        keys.add("判断");
        keys.add("抽象");
        keys.add("闷骚");
        keys.add("牛逼");
        keys.add("无敌");
        Collections.shuffle(keys);

        List<String> values = new ArrayList<>();
        values.add("50%");
        values.add("60%");
        values.add("70%");
        values.add("80%");
        values.add("90%");
        values.add("100%");
        Collections.shuffle(values);

        for (int i = 1; i <= 4; i++) {
            Dimensions dimensions = new Dimensions();
            dimensions.setKey(keys.remove(0));
            dimensions.setValue(values.remove(0));
            dimensionsList.add(dimensions);
        }
        return dimensionsList;
    }
}
